package com.lh.springcloud.alibaba.service.impl;

import com.lh.springcloud.alibaba.domain.CommonResult;
import com.lh.springcloud.alibaba.domain.Order;
import com.lh.springcloud.alibaba.mapper.OrderMapper;
import com.lh.springcloud.alibaba.service.AccountService;
import com.lh.springcloud.alibaba.service.OrderService;
import com.lh.springcloud.alibaba.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StorageService storageService;

    @Autowired
    private AccountService accountService;

    //查询订单，用于测试
    @Override
    public CommonResult queryAll(Order order) {
        List<Order> orderList = orderMapper.queryAll(order);
        return new CommonResult<>(200, "查询订单成功", orderList);
    }

    @Override
    @GlobalTransactional
    public void create(Order order) {
        log.info("开始创建订单..........");
        orderMapper.create(order);

        //远程调用库存服务扣减库存
        log.info("准备扣减库存........");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("扣减库存成功........");

        //远程调用账户服务扣减余额
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("扣减余额成功........");

        //修改订单状态
        log.info("订单修改成功........");
        orderMapper.updateMoney(order.getUserId(), false);
        log.info("order-service中修改订单状态结束..........");
        log.info("下单结束...........");

    }
}
